<template>
  <div class="right-menu">
    <el-dropdown class="avatar-container" trigger="click">
      <div class="avatar-wrapper">
        <div class="user-avatar">
          <!-- <img :src="avatar+'?imageView2/1/w/80/h/80'" style="width: 100%;"> -->
          <!-- <i class="el-icon-picture"></i> -->
          <!-- <div class="avatar">{{name}}</div> -->
          <el-avatar size="medium" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
        </div>
        <div style="color: #888888;z-index: 999;height: 50px;display: flex;flex-direction: column;align-items: center;justify-content: center;">
          <div style="cursor: pointer;line-height: 20px;height: 20px;width: 100%;color: #818181;overflow: hidden;">{{name}}</div>
          <div style="cursor: pointer;line-height: 20px;height: 20px;width: 100%;">{{orgName?orgName:org}}</div>
        </div>
        <i class="el-icon-caret-bottom" />
      </div>
      <el-dropdown-menu v-if="userInfoShow" slot="dropdown" class="user-dropdown">
        <el-dropdown-item divided @click.native="pwdModel=true">
          <span style="display:block;">密码修改</span>
        </el-dropdown-item>
        <el-dropdown-item divided @click.native="logout">
          <span style="display:block;">退出登录</span>
        </el-dropdown-item>
      </el-dropdown-menu>
      <el-dropdown-menu v-else slot="dropdown" class="user-dropdown">
        <el-dropdown-item divided @click.native="goback2provence">
          <span style="display:block;">返回本局</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <el-drawer
      title="密码变更"
      :visible.sync="pwdModel"
      direction="rtl"
      :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="150px" inline-message :rules="rules">
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="form.oldPwd" :type="type" style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="form.newPwd" :type="type" style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input v-model="form.confirmPwd" :type="type" style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-s-promotion" @click="passwordUpdate">提交</el-button>
          <el-button type="primary" icon="el-icon-view" @mouseover.native="type='text'" @mouseout.native="type='password'">查看密码</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer
      title="角色切换"
      size="300px"
      :visible.sync="roleModel"
      direction="rtl">
      <div style="padding: 20px;display: flex;flex-direction: column;">
        <el-button style="margin: 10px;" @click="handleRole(item)" :type="currentRole==item.roleId?'primary':''" v-for="item,index in roleData" :key="index">{{dict_role[item.roleId%14]}}</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {passwordChange,getRole4currentUser,changeRole} from '@/api/person.js'
import {back2provence} from '@/api/statistics.js'
import getDefaultState from '@/store/modules/user.js'
import {
  setToken,
} from '@/utils/auth'
export default {
  computed: {
    ...mapGetters([
      'avatar',
      'name',
      'org',
    ]),
    userInfoShow() {
      let statisticsMenu = window.sessionStorage.getItem('statisticsMenu')
      if(statisticsMenu=='true'){
        return true
      }else{
        return false
      }
    },
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.form.confirmPwd !== '') {
          this.$refs.form.validateField('confirmPwd');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.newPwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      orgName: window.sessionStorage.getItem('orgName'),
      type: 'password',
      form: {
        oldPwd: '',
        newPwd: '',
        confirmPwd: '',
      },
      pwdModel: false,
      rules: {
        oldPwd: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        newPwd: [
          { validator: validatePass, trigger: 'blur' },
        ],
        confirmPwd: [
          { validator: validatePass2, trigger: 'blur' },
        ]
      },
      dict_role: getDefaultState.state.dict_role,
      roleModel: false,
      roleData: [],
      currentRole: window.localStorage.getItem('roleId')
    }
  },
  methods: {
    goback2provence() {
      back2provence().then(res=>{
        setToken(res.data.token)
        window.sessionStorage.setItem('statisticsMenu',true)
        window.sessionStorage.removeItem('orgName')
        this.$router.push('/statistics/viewStatistics_org')
        setTimeout(()=>{
          window.location.reload()
        },200)
      })
    },
    handleRole(item) {
      changeRole({targetRoleId:item.roleId}).then((res)=>{
        if(res.code === 200){
          window.localStorage.setItem('roleId',res.data.roleId)
          window.sessionStorage.setItem('roleId',res.data.roleId)
          window.localStorage.setItem('userId',res.data.userId)
          window.sessionStorage.setItem('userId',res.data.userId)
          this.$store.dispatch('user/getMenu',{userId:res.data.userId,roleId:res.data.roleId}).then((res)=>{
            window.location.reload()
          })
        }
      })
    },
    passwordUpdate() {
      this.$refs.form.validate((valid) => {
        if(valid){
          let data = {
            old: this.form.oldPwd,
            newP: this.form.newPwd,
            confirm: this.form.confirmPwd,
          }
          passwordChange(data).then(res=>{
            if(res.code === 200){
              this.$message.success(res.data)
            }else{
              this.$message.error(res.data)
            }
          })
        }else{
          return false
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
      .then(_ => {
        done();
      })
      .catch(_ => {});
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login`)
      window.sessionStorage.removeItem('roleId')
      window.sessionStorage.removeItem('sessionDocDataIds')
      window.sessionStorage.removeItem('playerList')
      window.sessionStorage.removeItem('playerPdfNum')
      window.sessionStorage.removeItem('pdfNum')
    }
  }
}
</script>

<style lang="scss" scoped>
  .right-menu {
    float: right;
    height: 100%;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        height: 50px;
        margin-top: 5px;
        position: relative;
        display: flex;
        align-items: center;
        font-size: 80%;

         .index-help{
           display: flex;
           align-items: center;
           justify-content: center;
           float: right;
           border-right: 1px solid #eeeeee;
           margin-right: 10px;
           div{
             margin-right: 10px;
           }
         }
        .user-avatar {
          cursor: pointer;
          width: 35px;
          height: 35px;
          border-radius: 50%;
          background-color: #eeeeee;
          text-align: center;
          line-height: 35px;
          margin-right: 15px;
          overflow: hidden;
          .avatar{
            font-size: 18px;
            animation-name: nameAvatar;
            animation-duration: 15s;
            animation-timing-function: linear;
            animation-fill-mode: forwards;
            animation-iteration-count: infinite;
          }
        }
        @keyframes nameAvatar {
          0% {
            transform: translateX(1px);
          }
          50% {
            transform: translateX(-150px);
          }
          100% {
            transform: translateX(1px);
          }
        }
        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }

</style>
